<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中环创联移动充电桩调度系统</title>
</head>
<body>
    <img src="../static/img/logo.jpg" alt="公司Logo" class="logo" style="width: 30%; height: 50px;">
    <div class="main">

        <div class="title">调度系统</div>

        <div class="selectmap">
            <select id="mapSelect" onchange="DisplayMap()">
                <option value="">选择一个地图</option>
            </select>
            <select id="RobotSelect" onchange="UpdateRobot()">
                <option value="">选择需要控制的机器人</option>
            </select>
            <div class="robotinfo">剩余电量：50%</div>
            <button class="gohome">回去充电</button>
            <button class="disable">电机断电</button>
            <button id="nav" onclick="PostGoal()">发点导航</button>
            <button id="setParking" onclick="SetParking()">设置停车位</button>
            <button id="setCharge" onclick="SetCharge()">设置充电区</button>
            <input id="inputId" type="number" value=1>

            <div id="goalText">0,0</div>
        </div>

        <div class="display" id="display">
            <div class="image-container" id="map"></div>
        </div>
    </div>
    <style>
        body {
          background: linear-gradient(
            to right, 
            #00ff00, 
            #03fcb5); /* 从左到右的绿色渐变 */
        }
        button{
            border-radius: 20px;/*圆角效果*/
        }
        .main{
            width:98%;/* 自适应网页 */
            height:600px;/*高度不能百分比缩放*/
            background-color: rgb(249, 248, 244);
            border-radius: 20px;/*圆角效果*/
            margin-top: 20px;/*外边距*/
            margin-left: 1%;
            padding-left: 0;/*内边距*/
            padding-top: 10px;
            box-sizing: border-box;
        }
        .title{
            text-align: center;
            font-size: 30px;
            background: linear-gradient(
            to left, 
            #048ef7, 
            #03fcb5); /* 从左到右的渐变 */
            width:96%;
            margin-left: 2%;
            border-radius: 20px;/*圆角效果*/
            box-sizing: border-box;
        }
        .selectmap{
            background: linear-gradient(
            to left, 
            #048ef7, 
            #03fcb5); /* 从左到右的渐变 */
            margin-top: 10px;/*外边距*/
            margin-left: 2%;
            padding-top: 10px;
            padding-bottom: 10px;
            width:94%;
            padding-left: 20px;
            border-radius: 20px;/*圆角效果*/
            display: flex; /* 使用Flexbox布局 */
            align-items: center; /* 垂直居中对齐 */
            justify-content: flex-start; /* 从左到右排列 */
        }
        .selectmap > *:not(:last-child) {
            margin-right: 10px; /* 为除了最后一个子元素之外的所有子元素添加右边距 */
        }
        .display{
            background-color: black;
            margin-top: 10px;/*外边距*/
            margin-left: 2%;
            width:94%;
            height: 450px;
            border-radius: 20px;/*圆角效果*/
            display: flex;
            justify-content: center;
            overflow-x: scroll; /* 允许水平滚动 */
            overflow-y: scroll; 
        }
        .robot-model {
            width: 20px; /* 宽度 */
            height: 20px; /* 高度为宽度 */
            background-color: rgba(255, 255, 255, 0); /* 背景颜色 */
            color: rgb(186, 145, 10); /* 字体颜色为黄色 */
            font-weight: bold; /* 字体加粗 */
            text-align: center; /* 文本水平居中 */
            vertical-align: middle; /* 内容垂直居中 */
            border: 5px solid transparent; /* 初始边框为透明 */
            border-image: linear-gradient(to right, #ff9900, #ffcc00) 1; /* 渐变色边框 */
            border-image-slice: 1; /* 边框宽度 */
            border-radius: 10%; /* 保持圆形 */
        }
        .image-container {
            background-size: contain; /* 图片将保持其原始比例并尽可能缩放以适应div */
            background-position: center; /* 图片将居中显示 */
            background-repeat: no-repeat; /* 图片不会重复 */
            position: relative;
        }


    </style>

    <script>
        var timer=100;//10ms定时器
        var RobotselectElement = document.getElementById('RobotSelect');
        var MapselectElement = document.getElementById('mapSelect');
        var MapElement = document.getElementById('map')

        var GoalX;
        var GoalY;
        var RobotId;

        function UpdateRobot(){
            RobotId=document.getElementById('RobotSelect').value;
        }

        function SetParking(){
            fetch('/post-goal',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({'x':GoalX,'y':GoalY,'id':document.getElementById('inputId').value,'type':'parking','map': document.getElementById('mapSelect').value})
            })
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
            
        }

        function SetCharge(){
            fetch('/post-goal',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({'x':GoalX,'y':GoalY,'id':document.getElementById('inputId').value,'type':'charge','map':document.getElementById('mapSelect').value})
            })
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));

        }

        function PostGoal(){
            fetch('/post-goal',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({'x':GoalX,'y':GoalY,'id':RobotId,'type':'robot'})
            })
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
        }

        function DisplayMap() {
            var mapName = document.getElementById('mapSelect').value;
            if (!mapName) return;
            var mapDiv = document.getElementById('map');

            // 设置背景图片的路径
            mapDiv.style.backgroundImage = 'url("static/img/' + mapName + '.jpg")';

            // 获取图片的宽度和高度
            var img = new Image();
            img.src = 'static/img/' + mapName + '.jpg'
            img.onload = function() {
                // 设置长宽
                mapDiv.style.width = img.width+'px';
                mapDiv.style.height = img.height+'px';
            };

            // 添加点击事件监听器
            mapDiv.addEventListener('click', function(event) {
                GoalX = event.offsetX; // 获取鼠标点击位置相对于图片的X坐标
                GoalY = event.offsetY; // 获取鼠标点击位置相对于图片的Y坐标
                document.getElementById('goalText').textContent=GoalX+','+GoalY;
            });
        }


        function GetRobotList() {
            fetch('/datajson')
                // 尝试获取请求
                .then(response => response.json())
                .then(RobotList => {
                    // 确保元素存在
                    if (RobotselectElement && MapselectElement) {
                        RobotList.forEach(function(RobotData) {
                            //更新选择框
                            if(!document.getElementById("Robotoption"+RobotData['id'])){
                                var Robotoption = document.createElement('option');
                                Robotoption.id = 'Robotoption'+RobotData['id']
                                Robotoption.value = RobotData['id'];
                                Robotoption.text = RobotData['id'];
                                RobotselectElement.appendChild(Robotoption);
                            }
                            if(!document.getElementById('mapoption'+RobotData['map'])){
                                var mapoption = document.createElement('option');
                                mapoption.id='mapoption'+RobotData['map'];
                                mapoption.value = RobotData['map'];
                                mapoption.text = RobotData['map'];
                                MapselectElement.appendChild(mapoption);
                            }
                            // 机器人在线且在当前地图
                            if(document.getElementById('mapSelect').value===RobotData['map'] && RobotData['disable']!==0)
                            {
                                // 更新机器人模型
                                if(!document.getElementById(RobotData['type']+RobotData['id'])){
                                    var RobotModel = document.createElement('div');
                                    RobotModel.id=RobotData['type']+RobotData['id'];
                                    RobotModel.textContent =RobotData['id'];
                                    RobotModel.className = 'robot-model'; // 应用CSS类
                                    if (RobotData['type']=='parking')
                                    {
                                        RobotModel.style.color="rgb(0, 145, 10)";
                                    }
                                    if (RobotData['type']=='charge')
                                    {
                                        RobotModel.style.color="rgb(255, 145, 10)";
                                    }
                                    
                                    MapElement.appendChild(RobotModel);
                                }
                                // 更新机器人位置
                                else
                                {
                                    var RobotModel = document.getElementById(RobotData['type']+RobotData['id']);
                                    var x=RobotData['x'];
                                    var y=RobotData['y'];
                                    // 设置机器人模型的位置
                                    RobotModel.style.position = 'absolute'; // 确保可以绝对定位
                                    RobotModel.style.left = (x-10) + 'px'; // 设置模型左边缘的位置
                                    RobotModel.style.top = (y-10) + 'px'; // 设置模型顶部的位置
                                    
                                }
                            }
                            else
                            {
                                var RobotModel = document.getElementById(RobotData['type']+RobotData['id']);
                                // 如果元素存在，则从其父元素中删除
                                if (RobotModel) {
                                    RobotModel.parentNode.removeChild(RobotModel);
                                }
                            }
                            

                        });
                    } else {
                        console.error('RobotSelect or mapSelect element not found');
                    }
                })
                .catch(error => console.error('Error fetching robot list:', error));
        }

        // 每隔一段时间刷新数据
        setInterval(GetRobotList, 500);

        //只执行一次
        document.addEventListener('DOMContentLoaded', GetRobotList);
    </script>

</body>
</html>